<template>
  <a-card :bordered="false">
    <a-row :gutter="{ md: 8, lg: 24, xl: 32 }">
      <a-col :span="6">
        <a-form-item field="status" label="狀態">
          <a-select v-model="searchForm.status" @change="init(1)" placeholder="請選擇狀態" alow-clear>
            <a-option label="全部" :value="-1" />
            <a-option label="上線" :value="1" />
            <a-option label="下線" :value="0" />
          </a-select>
        </a-form-item>
      </a-col>
      <a-col :span="6">
        <a-button v-auth="[1, 2]" type="primary" style="margin: 0 10px" @click="openAddPopup">添加</a-button>
      </a-col>
    </a-row>

    <div ref="crudContentRef">
      <a-table
        :loading="loading"
        :scroll="{ x: '100%', y: '100%' }"
        :columns="columns"
        row-key="id"
        :pagination="false"
        :data="data">
        <template #imageUrl="{ record }">
          <a-image width="80" height="60" fit="contain" :src="record.imageUrl" />
        </template>
        <template #imageUrl2="{ record }">
          <a-image width="80" height="60" fit="contain" :src="record.imageUrl2" />
        </template>
        <template #linkUrl="{ record }">
          <a-link target="_blank" :href="record.linkUrl">{{ record.linkUrl }}</a-link>
        </template>
        <template #status="{ record }">
          {{ !record.status ? '下線' : '上線' }}
        </template>
        <template #ctime="{ record }">
          {{ dateFormat(record.ctime) }} <br />
          {{ dateFormat(record.mtime) }}
        </template>
        <template #optional="{ record }">
          <a-link v-auth="[1, 2]" @click="openEditPopup(record)"> 編輯 </a-link>
          <a-link
            v-auth="[1, 2]"
            :status="record.status == 1 ? 'danger' : 'success'"
            @click="changeBannerStatus(record)">
            {{ record.status == 1 ? '下線' : '上線' }}
          </a-link>
          <a-popconfirm content="確定刪除嗎？" @before-ok="deleteBanner(record)" type="warning">
            <a-link v-auth="[1, 2]" status="danger"> 刪除 </a-link>
          </a-popconfirm>
        </template>
      </a-table>
    </div>
    <div class="mt-2 text-right" v-if="data.length > 0">
      <a-pagination
        :total="pageObj.total"
        show-total
        show-page-size
        :page-size-options="[10, 20, 30, 50, 100]"
        @page-size-change="pageSizeChangeHandler"
        @change="pageChangeHandler"
        row-key="id"
        v-model:current="pageObj.page"
        :page-size="pageObj.pageSize"
        style="display: inline-flex" />
    </div>
    <a-modal
      v-model:visible="visible"
      :title="type == 'add' ? '添加' : '編輯'"
      width="600px"
      :ok-loading="btnLoading"
      @cancel="close"
      @before-ok="submit">
      <a-form ref="formRef" :model="formData" :rules="rules" :auto-label-width="true">
        <a-form-item label="標題" field="title">
          <a-input v-model="formData.title" placeholder="請輸入標題" />
        </a-form-item>
        <a-form-item label="封面圖" field="imageUrl">
          <a-upload
            list-type="picture-card"
            action=""
            :data="{
              type: 'imageUrl',
            }"
            :limit="1"
            @before-upload="imageUpload"
            @change="handleChange"
            :custom-request="customRequest"
            :file-list="fileList"
            image-preview />
        </a-form-item>
        <a-form-item label="移動端封面圖" field="imageUrl2">
          <a-upload
            list-type="picture-card"
            action=""
            :data="{
              type: 'imageUrl2',
            }"
            :limit="1"
            @change="handleChange2"
            @before-upload="imageUpload"
            :custom-request="customRequest"
            :file-list="fileList2"
            image-preview />
        </a-form-item>
        <a-form-item label="連結地址" field="linkUrl">
          <a-input v-model="formData.linkUrl" placeholder="請輸入連結地址" />
        </a-form-item>
        <a-form-item label="排序" field="priority">
          <a-input-number v-model="formData.priority" placeholder="請輸入排序" />
        </a-form-item>
        <a-form-item label="狀態" field="status">
          <a-radio-group v-model="formData.status" type="button">
            <a-radio :value="1">上線</a-radio>
            <a-radio :value="0">下線</a-radio>
          </a-radio-group>
        </a-form-item>
      </a-form>
    </a-modal>
  </a-card>
</template>

<script setup>
import { ref, reactive, onMounted, computed, nextTick } from 'vue'
import { Message } from '@arco-design/web-vue'
import configApi from '@/api/config'
import tool from '@/utils/tool'
const fileList = ref([])
const fileList2 = ref([])
const pageObj = reactive({
  page: 1,
  pageSize: 10,
  total: 0,
})
const handleChange2 = (value) => {
  if (!value.length) {
    formData.value.imageUrl2 = ''
  }
}
const handleChange = (value) => {
  if (!value.length) {
    formData.value.imageUrl = ''
  }
}
const imageUpload = (fileItem, b) => {
  if (fileItem.size / 1024 / 1024 > 1) {
    Message.error('圖片大小不能超過1MB')
    return false
  }
  return true
}
const customRequest = async (option) => {
  const { onProgress, onError, onSuccess, fileItem, name } = option
  const xhr = new XMLHttpRequest()
  if (xhr.upload) {
    xhr.upload.onprogress = function (event) {
      let percent
      if (event.total > 0) {
        // 0 ~ 1
        percent = event.loaded / event.total
      }
      onProgress(percent, event)
    }
  }
  const token = tool.local.get('token')
  xhr.onerror = function error(e) {
    onError(e)
  }
  xhr.onload = function onload() {
    if (xhr.status < 200 || xhr.status >= 300) {
      return onError(xhr.responseText)
    }
    let response = JSON.parse(xhr.response)
    if (response.code == 0) {
      // 成功
      if (option.data.type == 'imageUrl') {
        formData.value.imageUrl = response.data
      } else if (option.data.type == 'imageUrl2') {
        formData.value.imageUrl2 = response.data
      }
    } else {
      // 失敗
      if (response.code === 1002 || response.code === 1004) {
        Message.error(response.message || response.msg)
        router.push({ name: 'login' })
      } else {
        Message.error(response.message || response.msg)
      }
    }
    onSuccess(xhr.response)
  }

  const formFileData = new FormData()
  formFileData.append(name || 'file', fileItem.file)
  const baseUrl = import.meta.env.VITE_APP_BASE_URL
  xhr.open('post', baseUrl + 'api/v1/admin/image/upload', true)
  xhr.setRequestHeader('Authorization', `Bearer ${token}`)
  xhr.send(formFileData)

  return {
    abort() {
      xhr.abort()
    },
  }
}
const searchForm = reactive({
  status: -1,
})

const columns = ref([
  {
    title: '標題',
    dataIndex: 'title',
    ellipsis: true,
  },
  {
    title: '封面圖',
    dataIndex: 'imageUrl',
    slotName: 'imageUrl',
    width: 100,
  },
  {
    title: '移動端封面圖',
    dataIndex: 'imageUrl2',
    slotName: 'imageUrl2',
    width: 120,
  },
  {
    title: '連結地址',
    dataIndex: 'linkUrl',
    slotName: 'linkUrl',
    ellipsis: true,
  },

  {
    title: '狀態',
    dataIndex: 'status',
    slotName: 'status',
    align: 'center',
    width: 80,
  },
  {
    title: '排序',
    dataIndex: 'priority',
    width: 80,
    align: 'center',
  },
  {
    title: '創建/更新時間',
    dataIndex: 'ctime',
    slotName: 'ctime',
    width: 170,
  },
  {
    title: '操作',
    slotName: 'optional',
    width: 170,
  },
])
const rules = reactive({
  title: [{ required: true, message: '請輸入標題' }],
  imageUrl: [{ required: true, message: '請輸入封面圖' }],
  imageUrl2: [{ required: true, message: '請輸入移動端封面圖' }],
})
const type = ref('add')
const visible = ref(false)
const btnLoading = ref(false)
const formRef = ref(null)

const formData = ref({
  title: '',
  imageUrl: '',
  imageUrl2: '',
  linkUrl: '',
  priority: 0,
  status: 0,
})
const openAddPopup = () => {
  type.value = 'add'
  fileList.value = []
  fileList2.value = []
  formData.value = {
    title: '',
    imageUrl: '',
    imageUrl2: '',
    linkUrl: '',
    priority: 0,
    status: 0,
  }
  visible.value = true
}
const openEditPopup = (row) => {
  type.value = 'edit'
  fileList.value = [
    {
      url: row.imageUrl,
    },
  ]
  fileList2.value = [
    {
      url: row.imageUrl2,
    },
  ]
  formData.value = {
    id: row.id,
    title: row.title,
    imageUrl: row.imageUrl,
    imageUrl2: row.imageUrl2,
    linkUrl: row.linkUrl,
    priority: row.priority,
    status: row.status,
  }
  visible.value = true
}
const close = () => {
  visible.value = false
  btnLoading.value = false
}
const submit = async (done) => {
  if (formData.value.priority > 2147483647 || formData.value.priority < -2147483648) {
    Message.error('排序輸入超出範圍')
    return done(false)
  }
  const validate = await formRef.value?.validate()
  if (validate) return done(false)
  if (type.value === 'add') {
    try {
      await configApi.createBanner(formData.value)
      close()
      Message.success(`添加成功！`)
      init()
    } catch (error) {
      btnLoading.value = false
      done(false)
    }
  } else {
    try {
      await configApi.updateBanner(formData.value)
      close()
      Message.success(`修改成功！`)
      init()
    } catch (error) {
      btnLoading.value = false
      done(false)
    }
  }
}
const changeBannerStatus = async (row) => {
  loading.value = true
  try {
    await configApi.changeBannerStatus({
      ...row,
      status: row.status === 0 ? 1 : 0,
    })
    loading.value = false
    row.status = row.status === 0 ? 1 : 0
    Message.success(`修改成功！`)
  } catch (error) {
    loading.value = false
  }
}
const deleteBanner = async (row) => {
  try {
    await configApi.deleteBanner(row.id)
    Message.success(`刪除成功！`)
    init()
  } catch (error) {
    return false
  }
}
const data = ref([])

const pageSizeChangeHandler = async (pageSize) => {
  pageObj.page = 1
  pageObj.pageSize = pageSize
  init()
}
const pageChangeHandler = async (currentPage) => {
  pageObj.page = currentPage
  init(currentPage)
}

const loading = ref(false)
const init = async (pageNum = 1) => {
  loading.value = true
  try {
    const res = await configApi.getBannerList({
      pageNum,
      pageSize: pageObj.pageSize,
      status: searchForm.status < 0 ? '' : searchForm.status,
    })

    loading.value = false
    pageObj.total = res.data.total
    pageObj.page = res.data.pageNum
    pageObj.pageSize = res.data.pageSize
    data.value = res.data.list
  } catch (error) {
    loading.value = false
  }
}
init()

const crudContentRef = ref()
onMounted(async () => {
  await nextTick(() => {
    window.addEventListener('resize', settingFixedPage, false)
    settingFixedPage()
  })
})
const settingFixedPage = () => {
  const workAreaHeight = document.querySelector('.work-area').offsetHeight
  let tableHeight = workAreaHeight - 24 - 32 - 56 - 24
  if (crudContentRef.value) {
    crudContentRef.value.style.height = tableHeight + 'px'
  }
}
const dateFormat = computed(() => {
  return (val) => {
    if (!val) return '-'
    return tool.dateFormat(val)
  }
})
</script>
<style>
.arco-upload-list-picture img {
  object-fit: contain;
}
</style>
